package com.seeyon.apps.kk.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.seeyon.ctp.common.exceptions.BusinessException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.encrypt.CoderFactory;
import com.seeyon.ctp.common.i18n.ResourceBundleUtil;
import com.seeyon.ctp.common.usermessage.pipeline.Message;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.Strings;
import com.seeyon.kk.utils.KkEmailStrongUtils;
import com.seeyon.v3x.mail.manager.MessageMailManager;
import com.seeyon.v3x.mail.util.Affix;
import com.seeyon.v3x.mail.util.AffixList;

public class KkEmailStrongManager extends BaseManager {
    private static final Log log = LogFactory.getLog(KkEmailStrongManager.class);

    private MessageMailManager messageMailManager;
    private OrgManager orgManager;
    private OrgManagerDirect orgManagerDirect;
    private FreemarkFlowManager freemarkFlowManager;
    private FormDataBaseManager kkBaseFormManager;
    private FormApi4Cap4 formApi4Cap4;

    public FormApi4Cap4 getFormApi4Cap4() {
        return formApi4Cap4;
    }

    public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
        this.formApi4Cap4 = formApi4Cap4;
    }

    public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
        this.kkBaseFormManager = kkBaseFormManager;
    }

    public MessageMailManager getMessageMailManager() {
        return messageMailManager;
    }

    public void setMessageMailManager(MessageMailManager messageMailManager) {
        this.messageMailManager = messageMailManager;
    }

    public OrgManager getOrgManager() {
        return orgManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public OrgManagerDirect getOrgManagerDirect() {
        return orgManagerDirect;
    }

    public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
        this.orgManagerDirect = orgManagerDirect;
    }

    public FreemarkFlowManager getFreemarkFlowManager() {
        return freemarkFlowManager;
    }

    public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
        this.freemarkFlowManager = freemarkFlowManager;
    }

    public int needEmailStrong(Message message, int size) {
        boolean need = false;
        Long ruleId = message.getMessageRuleId();
        Long affairId = message.getReferenceId();
        // 系统预制 送达提醒ruleKey = col.send; 超期提醒ruleKey =node.affair.overTerm
        if (StringUtils.isNotBlank(message.getMessageContent().getStateName())) {
            if (message.getMessageContent().getStateName().equals("回退")) {
                log.info("#强生客开，messages is size :" + size);
                if (size > 1)
                    if (message.getMessageContent().getKeys().size() < 2) {
                        String tempKey = (String) message.getMessageContent().getKeys().get(0)[0];
                        log.info("message.getMessageContent()：" + JSONArray.toJSONString(message.getMessageContent().getKeys()));
                        log.info("messageKey:" + tempKey);
                        if (!tempKey.equals("collaboration.message.stepBack") && !tempKey.equals("collaboration.appointStepBack.msg2Send"))
                            return 1;
                    }
            }
        }
        // 否则新增的key
        String ruleKey = "";
        if (ruleId == null) {
            List<Object[]> keys = message.getMessageContent().getKeys();
            if (keys != null && !keys.isEmpty()) {
                Object[] objects = keys.get(0);
                ruleKey = String.valueOf(objects[0]);
            }
        } else {
            ruleKey = ruleId.toString();
        }

        // 转发走系统邮件。不和催办一起验证，防止出现系统默认消息邮件
        if(StringUtils.equals(ruleKey,"col.send") && StringUtils.isBlank(message.getMessageContent().getStateName())){
            return -1;
        }
        try {
            List<Map<String, Object>> affairList = this.jdbcTemplate.queryForList("select * from CTP_AFFAIR where id=? OR OBJECT_ID =?", affairId, affairId);
            Map<String, Object> affair = affairList.get(0);
            String formAppId = MapUtils.getString(affair, "FORM_APP_ID");
            String formRecordId = MapUtils.getString(affair, "FORM_RECORDID");
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            FormBean emailFormBean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);

            Map<String, Object> params = Maps.newHashMap();
            params.put("ruleKey", ruleKey);
            params.put("formAppId", formAppId);
            params.put("key", message.getMessageContent().getStateName() == null ? "处理" : message.getMessageContent().getStateName());   // 区分处理还是 回退、终止
            log.info("#强生客开,获取邮箱规则：" + params);
            Map<String, Object> emailStrong = this.isCheck(params);
            if (emailStrong.isEmpty()) {
                return 1;
            }
            FormDataMasterBean data = this.cap4FormManager.findDataById(Long.valueOf(formRecordId),
                    Long.valueOf(formAppId), null);
            FormBean formBean = this.cap4FormManager.getForm(Long.valueOf(formAppId), false);
            Map<String, Object> formdata = data.getAllDataMap();
            // 邮件正文模板
            String templateString = MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("邮件正文").getName());
            String subject = MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("标题").getName());
            String tcMailMember = MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("收件人").getName());
            String ccMailMember = MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("抄送人").getName());
            String fileId = MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("附件").getName());
            // 获取邮箱地址
            List tcMailArray = getMail(replaceContent(tcMailMember, formBean, formdata, ""));
            List ccMailArray = getMail(replaceContent(ccMailMember, formBean, formdata, ""));
            // 邮件附件
            AffixList affixList = mailFile(fileId);
            // 检测邮箱增强是否启用
            if (!isCheckEmailStrong(
                    MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("是否启用").getName()))) {
                return -1;
            }

            boolean isMailUrl = this.isCheckEmailURL(MapUtils.getString(emailStrong, emailFormBean.getFieldBeanByDisplay("MAIL_URL").getName()));
            log.info("邮件链接是否启用：" + isMailUrl);
            // 提前写入邮件链接位置
            String remoteURL = message.getRemoteURL();
            Locale locale = null;
            try {
                locale = orgManagerDirect.getMemberLocaleById(message.getReceiverMember().getId());
            } catch (Exception e) {
                log.error("", e);
            }
            String mailInfoUrl = "";
            if (isMailUrl) {
                if (Strings.isNotBlank(remoteURL) && messageMailManager.isContentWithLink()) {
                    ResourceBundle rb = ResourceBundleUtil.getResourceBundle(
                            com.seeyon.ctp.common.usermessage.Constants.DEFAULT_MESSAGE_RESOURCE, locale);
                    mailInfoUrl = "<a href='" + remoteURL + "' target='_blank'>" + ResourceBundleUtil.getString(rb, "common.mail.click2content") + "</a>";
                }
            }
            log.info("邮件链接地址 mailInfoUrl：" + mailInfoUrl);
            Map<String, Object> parmas = Maps.newHashMap();
            // 转编码
            parmas.put("context", replaceContent(URLDecoder.decode(templateString, "utf-8"), formBean, formdata, mailInfoUrl));
            parmas.put("subject", MapUtils.getString(replaceContent(subject, formBean, formdata, ""), "context"));
            log.info("#强生客开，邮件增强初始化完成：" + parmas.toString() + "， tcMailArray=[" + tcMailArray + "]， ccMailArray=[" + ccMailArray + "]");
            need = this.sendStrongMail(message, parmas, tcMailArray, ccMailArray, affixList, isMailUrl);
            log.info("#强生客开，邮件增强发送成功！ flag :" + need);
        } catch (Exception e) {
            log.error("#强生客开，邮件增强错误:", e);
        }
        return 2;

    }

    /**
     * 验证增强是否启用
     *
     * @param parmas
     * @return
     */
    public boolean isCheckEmailStrong(String parmas) {
        try {
            String sql = new KkEmailStrongUtils().enumToName();
            Map<String, Object> params = Maps.newHashMap();
            params.put("id", parmas);
            List<Map> datList = JdbcAgentUtil.doQuery(sql, params);
            if (!datList.isEmpty()) {
                String flag = MapUtils.getString(datList.get(0), "name");
                if ("是".equals(flag))
                    return true;
            }
        } catch (Exception e) {
            log.error("#强生客开，邮件增强-验证是否启用错误:", e);
            return false;
        }
        return false;
    }


    /**
     * 验证详情链接是否显示
     *
     * @param parmas
     * @return
     */
    public boolean isCheckEmailURL(String parmas) {
        try {
            String sql = new KkEmailStrongUtils().enumToName();
            Map<String, Object> params = Maps.newHashMap();
            params.put("id", parmas);
            List<Map> datList = JdbcAgentUtil.doQuery(sql, params);
            if (!datList.isEmpty()) {
                String flag = MapUtils.getString(datList.get(0), "name");
                if ("启用".equals(flag))
                    return true;
            }
        } catch (Exception e) {
            log.error("#强生客开，邮件增强-验证是否启用错误:", e);
            return false;
        }
        return false;
    }

    /**
     * 格式化 变量说明
     */
    public String initFieldDescription(String appFormId) {
        FormBean formBean = this.cap4FormManager.getForm(Long.valueOf(appFormId), false);
        String varDesc = this.freemarkFlowManager.fltTemplateIntoString("emailstrong/varDesc.ftl", formBean);
        return varDesc;
    }

    /**
     * 检查 邮箱配置是否存在
     *
     * @param params
     * @return
     */
    public Map<String, Object> isCheck(Map<String, Object> params) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);
            StringBuilder sql = new StringBuilder();
            FormTableBean formTableBean = formBean.getMasterTableBean();
            sql.append("select * from " + formTableBean.getTableName());
            sql.append(" LEFT JOIN CTP_ENUM_ITEM ON CTP_ENUM_ITEM.ID = " + formBean.getFieldBeanByDisplay("FLOW_STATE").getName());
            sql.append(" where " + formBean.getFieldBeanByDisplay("唯一标识").getName() + "=:ruleKey ");
            sql.append(" and " + formBean.getFieldBeanByDisplay("FORM_APP_ID").getName() + "=:formAppId");
            sql.append(" and CTP_ENUM_ITEM.SHOWVALUE =:key");
            log.info("#强生客开，isCheck SQL:" + sql.toString());
            List<Map> datList = JdbcAgentUtil.doQuery(sql.toString(), params);
            if (!datList.isEmpty()) {
                result = datList.get(0);
            }
        } catch (Exception e) {
            log.error("#强生客开，邮件增强-查询邮箱增强数据错误:", e);
        }
        return result;
    }

    /**
     * 检查 邮箱配置是否存在
     *
     * @param params
     * @return
     */
    public Map<String, Object> isCheckTable(Map<String, Object> params) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);
            StringBuilder sql = new StringBuilder();
            FormTableBean formTableBean = formBean.getMasterTableBean();
            sql.append("select * from " + formTableBean.getTableName());
            sql.append(" where " + formBean.getFieldBeanByDisplay("唯一标识").getName() + "=:ruleKey ");
            sql.append(" and " + formBean.getFieldBeanByDisplay("FORM_APP_ID").getName() + "=:formAppId");
            List<Map> datList = JdbcAgentUtil.doQuery(sql.toString(), params);
            if (!datList.isEmpty()) {
                result = datList.get(0);
            }
        } catch (Exception e) {
            log.error("#强生客开，邮件增强-查询邮箱增强数据错误:", e);
        }
        return result;
    }

    /**
     * 创建底表数据
     *
     * @param code
     * @param params
     * @return formmainId
     */
    public String insertEamil(String code, Map<String, Object> params) {
        Long formmainId = 1L;
        try {
            String functionConfig = this.freemarkFlowManager.fltTemplateIntoString("emailstrong/functionConfig.ftl",
                    null);
            params.put("预制函数", functionConfig);
            formmainId = kkBaseFormManager.saveUnflowData(code, Constants.createUser, params);
            return formmainId + "";
        } catch (Exception e) {
            log.error("#强生客开，邮件增强-创建底表数据错误:", e);
        }
        return formmainId + "";
    }

    /**
     * 每次打开底表修改预制函数和变量说明
     *
     * @param params
     */
    public void updateMailFunction(Map<String, Object> params) {
        try {
            String functionConfig = this.freemarkFlowManager.fltTemplateIntoString("emailstrong/functionConfig.ftl",
                    null);
            params.put("预制函数", functionConfig);
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);
            StringBuilder sb = new StringBuilder("update ");
            log.info("#强生客开，更新邮件增强预制函数、变量说明,start");
            FormTableBean formTableBean = formBean.getMasterTableBean();
            sb.append(formTableBean.getTableName() + " set ");
            sb.append(formBean.getFieldBeanByDisplay("预制函数").getName() + "=?,");
            sb.append(formBean.getFieldBeanByDisplay("变量说明").getName() + "=? ");
            sb.append(" where " + formBean.getFieldBeanByDisplay("唯一标识").getName() + "=? and ");
            sb.append(formBean.getFieldBeanByDisplay("FORM_APP_ID").getName() + "=?");
            List list = new ArrayList();
            list.add(functionConfig); // 添加预制函数
            log.info("#强生客开，更新邮件增强预制函数、变量说明,预制函数=[" + JSONArray.toJSONString(functionConfig) + "]");
            list.add(MapUtils.getString(params, "变量说明"));
            list.add(MapUtils.getString(params, "唯一标识"));
            list.add(MapUtils.getString(params, "FORM_APP_ID"));
            log.info("#强生客开，更新邮件增强预制函数、变量说明,SQL 生成 ：" + sb.toString());
            JdbcAgentUtil.doUpdateOrInsert(sb.toString(), list);
            log.info("#强生客开，更新邮件增强预制函数、变量说明,end");
        } catch (BusinessException e) {
            log.info("#强生客开，更新邮件增强预制函数、变量说明:", e);
        }
    }

    /**
     * 发送邮件
     *
     * @param message
     * @param parmas  加强内容
     * @return
     */
    public boolean sendStrongMail(Message message, Map<String, Object> parmas, List tcMailArray, List ccMailArray, AffixList affixList, boolean isMailUrl) {
        boolean flag = false;
        String toEmail = message.getReceiverMember().getEmailAddress();
        if (Strings.isNotBlank(toEmail)) {
            String bodyContent = message.getBodyContent();
            // 不需要邮件标题做为 内容出现在正文区域
            /*if (Strings.isBlank(bodyContent)) {
                bodyContent = message.getContent();
            }*/

            String subject = message.getContent();
            Locale locale = null;
            try {
                locale = orgManagerDirect.getMemberLocaleById(message.getReceiverMember().getId());
            } catch (Exception e) {
                log.error("", e);
            }
            if (message.getType() != com.seeyon.ctp.common.usermessage.Constants.UserMessage_TYPE.SYSTEM.ordinal()) {
                ResourceBundle rb = ResourceBundleUtil.getResourceBundle(
                        com.seeyon.ctp.common.usermessage.Constants.DEFAULT_MESSAGE_RESOURCE, locale);
                subject = ResourceBundleUtil.getString(rb, "communication.send",
                        message.getSenderMember() != null ? message.getSenderMember().getName() : "");
            }

            StringBuffer mailContent = new StringBuffer();
            // shkk 使用自定义内容

            Map<String, Object> tempMap = MapUtils.getMap(parmas, "context");
            boolean isMailUrlFlag = MapUtils.getBoolean(tempMap, "isMailUrl");
            log.info("是否自定义链接：" + isMailUrlFlag);
            if (StringUtils.isNotBlank(MapUtils.getString(tempMap, "context"))) {
                mailContent.append(MapUtils.getString(tempMap, "context"));
            } else {
                mailContent.append(bodyContent);
            }
            tcMailArray.add(toEmail); // 添加默认收件人
            log.info("默认收件人：" + toEmail);
            // shkk 使用自定义标题
            if (StringUtils.isNotBlank(MapUtils.getString(parmas, "subject"))) {
                subject = MapUtils.getString(parmas, "subject");
            }
            String remoteURL = message.getRemoteURL();

            // 可配置详情链接位置，注释产品标准功能
            if (!isMailUrlFlag) {
                if (isMailUrl) {
                    if (Strings.isNotBlank(remoteURL) && messageMailManager.isContentWithLink()) {
                        ResourceBundle rb = ResourceBundleUtil.getResourceBundle(
                                com.seeyon.ctp.common.usermessage.Constants.DEFAULT_MESSAGE_RESOURCE, locale);

                        mailContent.append("<br><br><a href='" + remoteURL + "' target='_blank'>");
                        mailContent.append(ResourceBundleUtil.getString(rb, "common.mail.click2content"));
                        mailContent.append("</a>");
                    }
                }
            }
            flag = messageMailManager.sendMessageByMail(tcMailArray, ccMailArray, subject, mailContent.toString(),
                    message.getCreateDate(), affixList);
        }
        return flag;
    }

    /**
     * $***{${**}} 内容正文替换  or ${**}
     *
     * @param context
     * @return
     */
    public Map<String, Object> replaceContent(String context, FormBean formBean, Map<String, Object> formData, String mailIfonUrl) {
        Map<String, Object> resultMap = Maps.newHashMap();
        boolean flag = false; // 标记是否自定义设置邮件链接位置
        if (StringUtils.isBlank(context)) {
            return resultMap;
        }
        Pattern p = Pattern.compile("\\$(([\u4e00-\u9fa5]){0,20})\\{\\$\\{(.*?)\\}\\}");
        Matcher m = p.matcher(context);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String functionContext = m.group(1);// 规则中$值{${值}}中的值 分别为1,3
            String repContent = m.group(3);
            String str = "";
            // 规则验证
            if (-1 != repContent.indexOf("field")) {
                str = MapUtils.getString(formData, repContent);
            } else {
                try {
                    str = MapUtils.getString(formData, formBean.getFieldBeanByDisplay(repContent).getName());
                } catch (Exception e) {
                    log.error("#强生客开，邮件自定义函数获取数据错误：" + e.getMessage());
                }
            }
            // 下一步是替换并且把替换好的值放到sb中
            if (null != str && !"".equals(str)) {
                m.appendReplacement(sb, new KkEmailStrongUtils().getContext(functionContext, str));
            } else {
                m.appendReplacement(sb, "");
            }
        }
        m.appendTail(sb);
        log.info("#强生客开，邮件正文函数转换数据：" + sb.toString());
        StringBuffer sbResult = new StringBuffer();
        Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
        Matcher matcher = pattern.matcher(sb.toString());
        while (matcher.find()) {
            String group = matcher.group(1);// 规则中${值}中的 值 一样 的数据不
            String str = "";
            // 规则验证
            if (StringUtils.isNotBlank(group)) {
                if (-1 != group.indexOf("field")) {
                    str = MapUtils.getString(formData, group);
                } else {
                    if (group.equals("系统日期")) {
                        str = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                    } else if (group.equals("邮件链接")) {
                        str = mailIfonUrl;
                        flag = true;
                    } else {
                        try {
                            str = MapUtils.getString(formData, formBean.getFieldBeanByDisplay(group).getName());
                        } catch (Exception e) {
                            log.error("#强生客开，字段属性：" + group);
                            log.error("#强生客开，邮件获取数据错误：" + e.getMessage());
                        }
                    }
                }
                if (null != str && !"".equals(str)) {
                    if (-1L != str.indexOf("@")) {
                        if (-1L == str.indexOf(";")) {
                            str += ";";
                        }
                    } else if (-1L != str.indexOf("null") || -1L != str.indexOf("NULL")) {
                        str = "";
                    }
                    matcher.appendReplacement(sbResult, str);
                } else {
                    matcher.appendReplacement(sbResult, "");
                }
            }
        }
        log.info("#强生客开，邮件正文转换结果:" + sbResult.toString());
        matcher.appendTail(sbResult);
        resultMap.put("context", sbResult.toString());
        resultMap.put("isMailUrl", flag);
        return resultMap;
    }

    /**
     * 更新邮件正文为富文本内容 底层方法更新
     *
     * @param context
     */
    public String updateEamilContext(String id, String context) {
        try {
            Thread.sleep(1 * 1000);
            Map<String, Object> map = Maps.newHashMap();
            map.put("邮件正文", context);
            FlipInfo flipInfo = new FlipInfo(1, 20);
            FormBean bean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);
            Map<String, Object> where = new HashMap<String, Object>();
            where.put("ID", id);
            List<FormDataMasterBean> masterList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, where);
            String result = this.kkBaseFormManager.updateFormData(Constants.EmailStrong, masterList.get(0), map);
            log.info("#强生客开，更新富文本内容成功：" + result);
            return result;
        } catch (Exception e) {
            log.error("#强生客开，更新富文本内容错误：", e);
        }
        return "400";
    }

    /**
     * 获取富文本信息
     *
     * @param id
     * @return
     */
    public String getContext(String id) {
        try {
            FlipInfo flipInfo = new FlipInfo(1, 20);
            FormBean bean = formApi4Cap4.getFormByFormCode(Constants.EmailStrong);
            Map<String, Object> where = new HashMap<String, Object>();
            where.put("ID", id);
            List<FormDataMasterBean> masterList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, where);
            Map<String, Object> map = masterList.get(0).getAllDataMap();
            return MapUtils.getString(map, bean.getFieldBeanByDisplay("邮件正文").getName());
        } catch (Exception e) {
            log.error("#强生客开，获取富文本信息错误：", e);
        }
        return "";
    }

    /**
     * 获取抄送人或收件人邮箱
     *
     * @param map
     * @return
     */
    public List getMail(Map<String, Object> map) {
        List<String> mail = Lists.newArrayList();
        String memberId = MapUtils.getString(map, "context");
        if (StringUtils.isBlank(memberId)) return mail;
        if (-1 != memberId.indexOf("@")) {
            // 本身就是邮箱
            String[] mails = memberId.split(";");
            for (int i = 0; i < mails.length; i++) {
                mail.add(mails[i]);
            }
            return mail;
        }
        try {
            String[] member = memberId.split(",");
            String sql = "SELECT EXT_ATTR_2 as mail FROM ORG_MEMBER WHERE ID =:mail";
            for (int i = 0; i < member.length; i++) {
                Map<String, Object> params = Maps.newHashMap();
                params.put("mail", member[i]);
                List<Map> datList = JdbcAgentUtil.doQuery(sql, params);
                if (!datList.isEmpty()) {
                    mail.add(MapUtils.getString(datList.get(0), "mail"));
                }
            }
            return mail;
        } catch (Exception e) {
            log.error("#强生客开，查询抄送人邮箱错误：", e);
        }
        return mail;
    }

    /**
     * 邮件挂载附件
     *
     * @param fileId
     * @return
     */
    public AffixList mailFile(String fileId) {
        try {
            if (StringUtils.isBlank(fileId)) return null;
            String sql = "SELECT FILENAME ,FILE_URL, CONVERT(VARCHAR(10),CREATEDATE,23) as udate FROM CTP_ATTACHMENT WHERE SUB_REFERENCE =:fileId";
            AffixList affixList = new AffixList();
            Map<String, Object> params = Maps.newHashMap();
            params.put("fileId", fileId);
            List<Map> datList = JdbcAgentUtil.doQuery(sql, params);
            for (Map map : datList) {
                String[] fileNameAndType = MapUtils.getString(map, "filename").split("\\.");
                String date = LocalDate.parse(MapUtils.getString(map, "udate")).format(DateTimeFormatter.ofPattern("yyyy\\MM\\dd"));
                String fileUrl = "\\" + MapUtils.getString(map, "file_url");
                Affix affix = new Affix();
                affix.setFileName(fileNameAndType[0]);
                affix.setRealPath(getDownloadPath(date + fileUrl, fileNameAndType[1]));
                affixList.add(affix);
            }
            return affixList;
        } catch (Exception e) {
            log.error("#强生客开,查询附件错误：", e);
        }
        return null;
    }

    /**
     * 解密文件
     *
     * @param filePath
     * @param fileType
     * @return 解密后的文件路径
     */
    public String getDownloadPath(String filePath, String fileType) {
        String downloadPath = "";
        try {
            String basePath = SystemEnvironment.getBaseFolder() + "\\upload\\";
            File input = new File(basePath + filePath);
            downloadPath = basePath + filePath + "." + fileType;
            File out = new File(downloadPath);
            FileInputStream fin = new FileInputStream(input);
            FileOutputStream fop = new FileOutputStream(out);
            CoderFactory.getInstance().download(fin, fop);
            fop.flush();
            fop.close();
            log.info("#强生客开，邮件增强文件路径：" + downloadPath);
            return downloadPath;
        } catch (Exception e) {
            log.error("#强生客开,邮件文件解密错误：", e);
        }
        return downloadPath;
    }
}